package com.lgCore.client;

import com.lgCore.clientHandler.RpcMsgHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.concurrent.GenericFutureListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

//@Slf4j
//@Data
//@Service("NettyClient")
public class NettyClient {

    Logger log = LoggerFactory.getLogger(this.getClass());


    // 服务器ip地址
    private String host="192.168.20.149";
    // 服务器端口
    private int port=9986;
    private Channel channel;

    private Bootstrap b;
    private EventLoopGroup g;
    private GenericFutureListener<ChannelFuture> connectedListener;
    public NettyClient() {

        /**
         * 客户端的是Bootstrap，服务端的则是 ServerBootstrap。
         * 都是AbstractBootstrap的子类。
         **/

        /**
         * 通过nio方式来接收连接和处理连接
         */
        g = new NioEventLoopGroup();
    }

    /**
     * 重连
     */
    public void doConnect() {
        try {


//            int threadsNum = Runtime.getRuntime().availableProcessors() * 2;
//
//            Bootstrap bootstrap=new Bootstrap();
//            bootstrap.channel(NioSocketChannel.class);
//            bootstrap.option(ChannelOption.SO_KEEPALIVE,true);
//            bootstrap.group(eventLoopGroup);
//            bootstrap.remoteAddress(host,port);
//            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
//                @Override
//                protected void initChannel(SocketChannel socketChannel) throws Exception {
//                    ChannelPipeline pipeline = socketChannel.pipeline();
//                    pipeline.addLast("decoder", new CommonRpcDecoderHandler());
//                    pipeline.addLast("encoder", new CommonRpcEncoderHandler());
////                pipeline.addLast(new ObjectEncoder());
////                pipeline.addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
//                    pipeline.addLast("timeout",new IdleStateHandler(20, 10, 120));
//                    pipeline.addLast("handler", new NettyClientHandler(threadsNum));
//
////                socketChannel.pipeline().addLast(new IdleStateHandler(20,10,0));
////                socketChannel.pipeline().addLast(new ObjectEncoder());
////                socketChannel.pipeline().addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
////                socketChannel.pipeline().addLast(new NettyClientHandler(threadsNum));
//                }
//            });




            EventLoopGroup eventLoopGroup=new NioEventLoopGroup();
            b = new Bootstrap();

//            b.group(g);
            b.channel(NioSocketChannel.class);
            b.group(eventLoopGroup);
            b.option(ChannelOption.SO_KEEPALIVE, true);
//            b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
            b.remoteAddress(host, port);

            // 设置通道初始化
            b.handler(
                    new ChannelInitializer<SocketChannel>() {
                        public void initChannel(SocketChannel ch) {
//                            ch.pipeline().addLast("deCoder", new RpcProtobufDecoder());
//                            ch.pipeline().addLast("enCoder", new RpcProtobufEncoder());
//                            ch.pipeline().addLast("timeout",new IdleStateHandler(20, 10, 120));
//                            ch.pipeline().addLast("loginResponseHandler",loginResponceHandler);
                            ch.pipeline().addLast("chatMsgHandler",new RpcMsgHandler());
//                            ch.pipeline().addLast("exceptionHandler",exceptionHandler);
                        }
                    }
            );
            log.info("客户端开始连接 [疯狂创客圈IM]");
            ChannelFuture future =b.connect(host,port).sync();
            if (future.isSuccess()) {
                SocketChannel socketChannel;
                socketChannel = (SocketChannel)future.channel();
                System.out.println("connect server  成功---------");
                //发送心跳连接
//                RpcMsgProto.RpcMsg.Builder rpcMsg = RpcMsgProto.RpcMsg.newBuilder();
//                rpcMsg.setClientId("111111");
//                rpcMsg.setBusinessId("222222");
//                rpcMsg.setMsgType("2");
//                for(int i=0;i<10;i++){
//                    socketChannel.writeAndFlush("333333333333333333");
//                    System.out.println("发送成功");
//                    Thread.sleep(1000);
//                }
            }



        } catch (Exception e) {
            log.info("客户端连接失败!" + e.getMessage());
        }
    }

    public void close() {
        g.shutdownGracefully();
    }


//    public static void main(String[] args) {
//        new NettyClient().doConnect();
//    }
}
